require(sp)
require(rgdal)
load("02_03_m5s_meetup_vote_spatial_data.RData")
load("02_04_m5s_meetup_vote_analysis_fb_count_by_province_mar15.RData")
load("02_04_m5s_meetup_vote_analysis_fb_count_dist_by_province.RData")

# for (y in c('2013')) {
#   for (i in 2:ncol(fb_count[[y]])) {
#     fb_count[[y]][[i]][is.na(fb_count[[y]][[i]])] <-  0
#   }
# }

italy_map_2013 <- merge(italy_map_2013, fb_count_dist[['2013']], 
                        by = 'COD_PRO',
                        all.x = TRUE)

italy_df_2013 <- as.data.frame(italy_map_2013)
italy_df_2013$votes_ratio <- with(italy_df_2013, votes / voters)
italy_df_2013$members_ratio <- with(italy_df_2013, members / voters)
italy_df_2013$user_ratio <- with(italy_df_2013, `days_30liking_users` / voters)
italy_df_2013$post_ratio <- with(italy_df_2013, `days_30posts` / voters)
italy_df_2013$page_ratio <- with(italy_df_2013, sum(days_30posts > 0, na.rm = T) / voters)

mod0_wt_fb <-
  lm(data = subset(italy_df_2013, !is.na(days_90liking_users)), 
     log(votes) ~ log(voters) + log(days_90liking_users))
mod1_wt_fb <-
  lm(data = subset(italy_df_2013, !is.na(days_90liking_users)), 
     votes_ratio ~ log(voters) + log(members) + log(days_90liking_users))
mod2_wt_fb <-
  lm(data = subset(italy_df_2013, !is.na(days_90commenting_users)), 
     votes_ratio ~ log(voters) + log(members) + log(days_90commenting_users))

save(mod0_wt_fb, mod1_wt_fb, mod2_wt_fb, file = '02_05_m5s_meetup_vote_analysis_lm_mod_wt_fb.RData')

italy_map_2013$user_ratio <- italy_df_2013$user_ratio 
italy_map_2013$post_ratio <- italy_df_2013$post_ratio
italy_map_2013$page_ratio <- italy_df_2013$page_ratio

save(italy_map_2013, 
     file = '02_05_m5s_meetup_vote_analysis_spatial_model_wt_fb.RData')

